package mazewar.legacy;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;


/**
 *
 * @author jillsanluis
 */ 
class NetworkClientThread extends Thread {

    private Socket socket = null;
    private NetworkClient netClient = null;
    private ObjectInputStream streamIn = null;

    public NetworkClientThread(NetworkClient netClient, Socket socket) {
        this.netClient = netClient;
        this.socket = socket;

        // open the stream
        try {
            streamIn = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            System.out.println("Error getting input stream: " + e.getMessage());
            netClient.stop();
        }

        // now start running the thread
        this.start();
    }

    @Override
    public void run() {

        // just keep listening
        while (true) {
            try {
                netClient.handle((NetworkPacket) streamIn.readObject(), netClient);
            } catch (ClassNotFoundException e) {
                System.out.println("Listening error: " + e.getMessage());
                netClient.stop();
                break;
            } catch (IOException e) {
                System.out.println("Listening error: " + e.getMessage());
                netClient.stop();
                break;
            }
        }
    }

    public void close() {
        try {
            if (streamIn != null) {
                streamIn.close();
            }

        } catch (IOException e) {
            System.out.println("Error closing input stream: " + e.getMessage());
            netClient.stop();
        }
    }
}
